package com.github.postsanf.yinian.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.CoverThemeAdapter;
import com.github.postsanf.yinian.bean.CoverTheme;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.utils.UIHelper;
import com.github.postsanf.yinian.entity.YNCoverThemeResponse;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.WrapContentLinearLayoutManager;
import com.github.postsanf.yinian.utils.YNUrlHelper;
import com.github.postsanf.yinian.view.DetailRecyclerView;
import com.github.postsanf.yinian.widget.MyEditText;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

public class VoiceCardEditActivity extends BaseActivity implements View.OnClickListener {
    private int bmpw = 0; // 游标宽度
    private int offset = 0;// // 动画图片偏移量
    private int currIndex = 0;// 当前页卡编号
    private Animation animation = null;
    private ImageView iv_back;
    private SimpleDraweeView iv_voice_pic;
    private TextView tv_to_name;
    private LinearLayout myedittext_voicecard;
    private TextView tv_from_name;
    private LinearLayout timecard_cover_sub;
    private TextView timecard_cover_recommend;
    private TextView timecard_cover_more;
    private DetailRecyclerView cover_detail_horizontal;
    private LinearLayout timecard_elecment_sub;
    private LinearLayout time_card_edit_time;
    private LinearLayout time_card_edit_from;
    private LinearLayout timecard_pic_sub;
    private RecyclerView timecard_pic_sub_recy;
    private LinearLayout time_card_edit_cover;
    private LinearLayout time_card_edit_element;
    private LinearLayout time_card_edit_pic;
    private LinearLayout time_card_word;
    private CoverThemeAdapter ctAdapter;
    private List<CoverTheme> mCoverThemes = new ArrayList<>();
    private String coverUrl = "";
    private SimpleDraweeView time_card_edit_cover_pic;
    private ImageView cursor;
    private TextView timecard_upload;
    private LinearLayout time_card_mic;
    private LinearLayout time_card_to;
    private LinearLayout ll_to;
    private RelativeLayout voice_card_edit_kuang;
    private RelativeLayout ll_text;
    private MyEditText myEditText;
    private String imagelocal;
    private String micurl;
    private boolean mp3IsExist;
    private RelativeLayout rl_selector;
    private int miclenth = 0;
    private TextView tv_from;
    private TextView tv_to;
    private ImageView iv_time_card_edit_cover;
    private ImageView iv_time_card_edit_element;
    private ImageView iv_time_card_edit_pic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_voice_card_edit);
        registerBroadcastReceiver();
        initCursorPos();
        initView();
        GetAllOfficialCovers();
    }

    private void registerBroadcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.updataTimeCardEditPic);
        myIntentFilter.addAction(ACTIONs.actionMIcText);
        myIntentFilter.addAction(ACTIONs.actionUpdateCoverImg);
        myIntentFilter.addAction(ACTIONs.actionUpdateFromText);
        myIntentFilter.addAction(ACTIONs.actionCloseVoiceCard);
        myIntentFilter.addAction(ACTIONs.updateVoiceCardPic);
        this.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionUpdateCoverImg:
                    if (intent != null) {
                        coverUrl = intent.getStringExtra("url");
                        ImageOptHelper.showFrescoTodayshow(Uri.parse(YNUrlHelper.getCoverUrl2(VoiceCardEditActivity.this, coverUrl)), time_card_edit_cover_pic, VoiceCardEditActivity.this);
                    }
                    break;
                case ACTIONs.actionCloseVoiceCard:
                    finish();
                    break;
                case ACTIONs.updateVoiceCardPic:
                    imagelocal = intent.getStringExtra("imagelocal");
                    ImageOptHelper.showFrescoVoicePic(Uri.parse("file://" + imagelocal), iv_voice_pic, VoiceCardEditActivity.this);
                    break;
                case ACTIONs.actionUpdateFromText:
                    if (intent != null) {
                        String voice_card_word = intent.getStringExtra("time_card_word");
                        String time_card_edit_from = intent.getStringExtra("time_card_edit_from");
                        String time_card_to = intent.getStringExtra("time_card_to");
                        if (voice_card_word != null) {
                            myedittext_voicecard.removeAllViews();
                            myEditText.setTextColor(getResources().getColor(R.color.timecard_from_txcolor_drak));
                            if (!voice_card_word.equals("")) {
                                myEditText.setTypeface(Typeface.createFromAsset(getAssets(), "fzjl.TTF"));
                                myEditText.setText(voice_card_word);
                            } else {
                                myEditText.setText("");
                            }
                            myedittext_voicecard.addView(myEditText);
                        }
                        if (time_card_edit_from != null) {
                            tv_from_name.setTypeface(Typeface.createFromAsset(getAssets(), "fzjl.TTF"));
                            tv_from_name.setText(time_card_edit_from);
                        }
                        if (time_card_to != null) {
                            tv_to_name.setTypeface(Typeface.createFromAsset(getAssets(), "fzjl.TTF"));
                            tv_to_name.setText(time_card_to + ":");
                        }
                    }
                    break;
                case ACTIONs.actionMIcText:
                    mp3IsExist = intent.getBooleanExtra("isOK", false);
                    if (mp3IsExist) {
                        miclenth = MicActivity.timer;
                        micurl = intent.getStringExtra("micUrl");
                    } else {
                        miclenth = 0;
                    }
                    break;
            }
        }
    };


    private void initView() {
        ll_to = (LinearLayout) findViewById(R.id.ll_to);
        voice_card_edit_kuang = (RelativeLayout) findViewById(R.id.voice_card_edit_kuang);
        LinearLayout.LayoutParams kuangParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, UIHelper.getVoiceCardHigh(this));
        kuangParams.setMargins(UIHelper.dip2px(this, 10),
                UIHelper.dip2px(this, 20),
                UIHelper.dip2px(this, 10), 0);
        voice_card_edit_kuang.setLayoutParams(kuangParams);
        ll_text = ((RelativeLayout) findViewById(R.id.ll_text));
        iv_back = ((ImageView) findViewById(R.id.iv_back));
        iv_back.setOnClickListener(this);
        rl_selector = ((RelativeLayout) findViewById(R.id.rl_selector));
        iv_voice_pic = ((SimpleDraweeView) findViewById(R.id.iv_voice_pic));
        RelativeLayout.LayoutParams picParams = new RelativeLayout.LayoutParams(UIHelper.getVoiceCardPicWidth(this), UIHelper.getVoiceCardPicHigh(this));
        picParams.addRule(RelativeLayout.CENTER_VERTICAL);
        picParams.leftMargin = UIHelper.dip2px(this, 20);
        iv_voice_pic.setLayoutParams(picParams);
        tv_to_name = ((TextView) findViewById(R.id.tv_to_name));

        myedittext_voicecard = ((LinearLayout) findViewById(R.id.myedittext_voicecard));
        myEditText = new MyEditText(this, Color.parseColor("#00000000"), 2.0f);
        myEditText.setTextSize(10);
        myedittext_voicecard.removeAllViews();
        myEditText.setTextColor(Color.parseColor("#000000"));
        myEditText.setText("   \n   \n   \n   ");
        myedittext_voicecard.addView(myEditText);

        tv_from = ((TextView) findViewById(R.id.tv_from));
        tv_from.setTypeface(Typeface.createFromAsset(getAssets(), "fzjl.TTF"));
        tv_from.setText("From:");
        tv_to = ((TextView) findViewById(R.id.tv_to));
        tv_to.setTypeface(Typeface.createFromAsset(getAssets(), "fzjl.TTF"));
        tv_to.setText("To:");
        tv_from_name = ((TextView) findViewById(R.id.tv_from_name));
        timecard_cover_sub = ((LinearLayout) findViewById(R.id.timecard_cover_sub));
        timecard_cover_recommend = ((TextView) findViewById(R.id.timecard_cover_recommend));
        timecard_cover_recommend.setOnClickListener(this);
        timecard_cover_more = ((TextView) findViewById(R.id.timecard_cover_more));
        timecard_cover_recommend.setOnClickListener(this);
        timecard_cover_more.setOnClickListener(this);
        timecard_upload = ((TextView) findViewById(R.id.timecard_upload));
        timecard_upload.setOnClickListener(this);
        time_card_edit_cover_pic = ((SimpleDraweeView) findViewById(R.id.time_card_edit_cover_pic));
        cover_detail_horizontal = ((DetailRecyclerView) findViewById(R.id.cover_detail_horizontal));
        WrapContentLinearLayoutManager horLayoutManager = new WrapContentLinearLayoutManager(this);
        horLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        cover_detail_horizontal.setLayoutManager(horLayoutManager);
        ctAdapter = new CoverThemeAdapter(this, mCoverThemes);
        cover_detail_horizontal.setHasFixedSize(true);
        cover_detail_horizontal.setAdapter(ctAdapter);
        ctAdapter.setOnItemClickLitener(new CoverThemeAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                coverUrl = mCoverThemes.get(position).getOfficialCoverPicture();
                time_card_edit_cover_pic.setVisibility(View.VISIBLE);
                ll_text.setVisibility(View.GONE);
                iv_voice_pic.setVisibility(View.GONE);
                ImageOptHelper.showFrescoTodayshow(Uri.parse(YNUrlHelper.getCoverUrl2(VoiceCardEditActivity.this, coverUrl)), time_card_edit_cover_pic, VoiceCardEditActivity.this);
            }
        });
        timecard_elecment_sub = ((LinearLayout) findViewById(R.id.timecard_elecment_sub));
        time_card_edit_time = ((LinearLayout) findViewById(R.id.time_card_edit_time));
        timecard_pic_sub = ((LinearLayout) findViewById(R.id.timecard_pic_sub));
        timecard_pic_sub_recy = ((RecyclerView) findViewById(R.id.timecard_pic_sub_recy));
        time_card_edit_cover = ((LinearLayout) findViewById(R.id.time_card_edit_cover));
        time_card_edit_cover.setOnClickListener(this);
        time_card_edit_element = ((LinearLayout) findViewById(R.id.time_card_edit_element));
        time_card_edit_element.setOnClickListener(this);
        time_card_edit_pic = ((LinearLayout) findViewById(R.id.time_card_edit_pic));
        time_card_edit_pic.setOnClickListener(this);
        time_card_word = ((LinearLayout) findViewById(R.id.time_card_word));
        time_card_to = ((LinearLayout) findViewById(R.id.time_card_to));
        time_card_edit_from = ((LinearLayout) findViewById(R.id.time_card_edit_from));
        time_card_mic = ((LinearLayout) findViewById(R.id.time_card_mic));
        time_card_mic.setOnClickListener(this);
        time_card_edit_from.setOnClickListener(this);
        time_card_to.setOnClickListener(this);
        time_card_word.setOnClickListener(this);
        if (getIntent() != null && !StringUtils.isEmpty(getIntent().getStringExtra("imagelocal"))) {
            imagelocal = getIntent().getStringExtra("imagelocal");
            ImageOptHelper.showFrescoVoicePic(Uri.parse("file://" + imagelocal), iv_voice_pic, VoiceCardEditActivity.this);
        }
        iv_time_card_edit_cover = ((ImageView) findViewById(R.id.iv_time_card_edit_cover));
        iv_time_card_edit_element = ((ImageView) findViewById(R.id.iv_time_card_edit_element));
        iv_time_card_edit_pic = ((ImageView) findViewById(R.id.iv_time_card_edit_pic));
    }

    //初始显示封面和图片
    private void initCoverBackImg() {
        time_card_edit_cover_pic.setVisibility(View.GONE);
        timecard_cover_sub.setVisibility(View.GONE);
        timecard_pic_sub.setVisibility(View.GONE);
        timecard_elecment_sub.setVisibility(View.VISIBLE);
        ll_text.setVisibility(View.VISIBLE);
        iv_voice_pic.setVisibility(View.VISIBLE);
        rl_selector.setVisibility(View.VISIBLE);
    }

    //初始化指示器位置
    public void initCursorPos() {
        cursor = (ImageView) findViewById(R.id.cursor);
        bmpw = BitmapFactory.decodeResource(getResources(), R.drawable.time_postcard_bar)
                .getWidth();// 获取图片宽度
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenW = dm.widthPixels;// 获取分辨率宽度
        offset = (screenW / 3 - bmpw) / 2;// 计算偏移量
        Matrix matrix = new Matrix();
        matrix.postTranslate(offset, 0);
        cursor.setImageMatrix(matrix);// 设置动画初始位置
        int one = offset * 2 + bmpw;
        animation = new TranslateAnimation(offset, one, 0, 0);
        animation.setFillAfter(true);
        animation.setDuration(300);
        cursor.startAnimation(animation);
        currIndex = 1;
    }

    private void GetAllOfficialCovers() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put("type", "1");
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.GetRecommendCover))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCoverThemeResponse resAlertBg = gson.fromJson(s, YNCoverThemeResponse.class);
                        if (ReqUtils.isSuccess(resAlertBg.getCode())) {
                            List<CoverTheme> YNTaglist = resAlertBg.getData();
                            mCoverThemes.clear();
                            mCoverThemes.addAll(YNTaglist);
                            ctAdapter.notifyDataSetChanged();
                            initCoverBackImg();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    @Override
    public void onClick(View v) {
        int one = offset * 2 + bmpw;
        int two = one * 2;
        switch (v.getId()) {
            case R.id.iv_back:
                new AlertDialog.Builder(VoiceCardEditActivity.this).setMessage("确定不要这张声音明信片了吗？")
                        .setPositiveButton(R.string.yn_app_ok, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                finish();
                            }
                        }).setNegativeButton(R.string.yn_app_cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                }).show();
                break;
            case R.id.timecard_upload:
                if (StringUtils.isEmpty(coverUrl)) {
                    showToast("选择封面后预览");
                    return;
                }
                Intent intentPre = new Intent(VoiceCardEditActivity.this, VoiceCardPreViewActivity.class);
                if (imagelocal != null) {
                    intentPre.putExtra("voicepic", imagelocal);
                }
                intentPre.putExtra("voiceCoverPic", coverUrl);
                intentPre.putExtra("voiceToName", tv_to_name.getText().toString());
                intentPre.putExtra("voiceFromName", tv_from_name.getText().toString());
                intentPre.putExtra("voiceContent", myEditText.getText().toString());
                intentPre.putExtra("mp3IsExist", mp3IsExist);
                intentPre.putExtra("micurl", micurl);
                intentPre.putExtra("audiotime", miclenth);
                startActivity(intentPre);
                break;
            case R.id.time_card_mic:
                Intent micIntent = new Intent(VoiceCardEditActivity.this, MicActivity.class);
                startActivityForResult(micIntent, 20);
                break;
            case R.id.time_card_word:
                Intent intent = new Intent(VoiceCardEditActivity.this, TimeCardwordActivity.class);
                intent.putExtra("time_card_word", "time_card_word");
                intent.putExtra("text_content", myEditText.getText().toString());
                startActivity(intent);
                break;
            case R.id.time_card_to:
                Intent intent1 = new Intent(VoiceCardEditActivity.this, TimeCardwordActivity.class);
                intent1.putExtra("time_card_to", "time_card_to");
                intent1.putExtra("text_content", tv_to_name.getText().toString());
                startActivity(intent1);
                break;
            case R.id.time_card_edit_from:
                Intent intent2 = new Intent(VoiceCardEditActivity.this, TimeCardwordActivity.class);
                intent2.putExtra("time_card_edit_from", "time_card_edit_from");
                intent2.putExtra("text_content", tv_from_name.getText().toString());
                startActivity(intent2);
                break;
            case R.id.timecard_cover_recommend:
                ll_text.setVisibility(View.GONE);
                cover_detail_horizontal.setVisibility(View.VISIBLE);
                timecard_cover_recommend.setTextColor(getResources().getColor(R.color.timecard_cover_tip_drak));
                timecard_cover_more.setTextColor(getResources().getColor(R.color.timecard_cover_tip_light));
                break;
            case R.id.timecard_cover_more:
                ll_text.setVisibility(View.GONE);
                timecard_cover_more.setTextColor(getResources().getColor(R.color.timecard_cover_tip_drak));
                timecard_cover_recommend.setTextColor(getResources().getColor(R.color.timecard_cover_tip_light));
                startActivity(new Intent(VoiceCardEditActivity.this, VoiceCardCoverMore.class));
                break;
            case R.id.time_card_edit_cover:
                iv_time_card_edit_cover.setImageResource(R.drawable.time_card_edit_cover_select);
                iv_time_card_edit_element.setImageResource(R.drawable.time_card_edit_element);
                iv_time_card_edit_pic.setImageResource(R.drawable.time_card_edit_pic);
                time_card_edit_cover_pic.setVisibility(View.VISIBLE);
                timecard_elecment_sub.setVisibility(View.GONE);
                timecard_pic_sub.setVisibility(View.GONE);
                timecard_cover_sub.setVisibility(View.VISIBLE);
                ll_text.setVisibility(View.GONE);
                iv_voice_pic.setVisibility(View.GONE);
                rl_selector.setVisibility(View.VISIBLE);
                if (currIndex == 1) {
                    animation = new TranslateAnimation(one, 0, 0, 0);
                } else if (currIndex == 2) {
                    animation = new TranslateAnimation(two, 0, 0, 0);
                }
                animation.setFillAfter(true);
                animation.setDuration(300);
                cursor.startAnimation(animation);
                currIndex = 0;
                break;
            case R.id.time_card_edit_element:
                iv_time_card_edit_cover.setImageResource(R.drawable.time_card_edit_cover);
                iv_time_card_edit_element.setImageResource(R.drawable.time_card_edit_element_select);
                iv_time_card_edit_pic.setImageResource(R.drawable.time_card_edit_pic);
                time_card_edit_cover_pic.setVisibility(View.GONE);
                timecard_cover_sub.setVisibility(View.GONE);
                timecard_pic_sub.setVisibility(View.GONE);
                timecard_elecment_sub.setVisibility(View.VISIBLE);
                ll_text.setVisibility(View.VISIBLE);
                iv_voice_pic.setVisibility(View.VISIBLE);
                rl_selector.setVisibility(View.VISIBLE);
                if (currIndex == 0) {
                    animation = new TranslateAnimation(offset, one, 0, 0);
                } else if (currIndex == 2) {
                    animation = new TranslateAnimation(two, one, 0, 0);
                }
                animation.setFillAfter(true);
                animation.setDuration(300);
                cursor.startAnimation(animation);
                currIndex = 1;
                break;
            case R.id.time_card_edit_pic:
                iv_time_card_edit_cover.setImageResource(R.drawable.time_card_edit_cover);
                iv_time_card_edit_element.setImageResource(R.drawable.time_card_edit_element);
                iv_time_card_edit_pic.setImageResource(R.drawable.time_card_edit_pic_select);
                time_card_edit_cover_pic.setVisibility(View.GONE);
                timecard_cover_sub.setVisibility(View.GONE);
                timecard_elecment_sub.setVisibility(View.GONE);
                timecard_pic_sub.setVisibility(View.VISIBLE);
                ll_text.setVisibility(View.VISIBLE);
                iv_voice_pic.setVisibility(View.VISIBLE);
                rl_selector.setVisibility(View.GONE);
                if (currIndex == 0) {
                    animation = new TranslateAnimation(offset, two, 0, 0);
                } else if (currIndex == 1) {
                    animation = new TranslateAnimation(one, two, 0, 0);
                }
                animation.setFillAfter(true);
                animation.setDuration(300);
                cursor.startAnimation(animation);
                currIndex = 2;
                intent2Activity(TimeGoodsAlbumActivity.class);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            mp3IsExist = data.getBooleanExtra("isOK", false);
            if (mp3IsExist) {
                micurl = data.getStringExtra("micUrl");
                miclenth = MicActivity.timer;
            } else {
                miclenth = 0;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        File file = new File(imagelocal);
        if (file.exists()) {
            file.delete();
        }
        unregisterReceiver(mBroadcastReceiver);
        MicActivity.mMp3FileName = "";
    }


    @Override
    protected void onResume() {
        super.onResume();
        sendBroadcast(new Intent(ACTIONs.actionCloseTimeGoodsAlbum));
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }


}
